package com.yuezhu.sweetdialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.Transformation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.yuezhu.global.ApplicationContext;
import com.yuezhu.R;
import com.yuezhu.util.LogUtils;
import com.yuezhu.util.MyToast;
import com.yuezhu.util.StringUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.List;


public class SweetAlertDialog extends Dialog implements View.OnClickListener,
		OnCheckedChangeListener {
	private View mDialogView;
	private AnimationSet mModalInAnim;
	private AnimationSet mModalOutAnim;
	private Animation mOverlayOutAnim;
	private Animation mErrorInAnim;
	private AnimationSet mErrorXInAnim;
	private AnimationSet mSuccessLayoutAnimSet;
	private Animation mSuccessBowAnim;
	private TextView mTitleTextView;
	private TextView mtit1, mtit2;
	private TextView mContentTextView;
	private String mTitleText;
	private String mTitleText1;
	private String mContentText;
	private boolean mShowCancel;
	private String mCancelText;
	private String mConfirmText;
	private int mAlertType;
	private TextView addTextView;
	private FrameLayout mErrorFrame;
	private FrameLayout mSuccessFrame;
	private SuccessTickView mSuccessTick;
	private ImageView mErrorX;
	private View mSuccessLeftMask;
	private View mSuccessRightMask;
	private Drawable mCustomImgDrawable;
	private ImageView mCustomImage;
	private Button mConfirmButton;
	private Button mCancelButton;
	private RelativeLayout mWarningFrame;
	private RadioGroup radioGroup;
	public static EditText driverName, driverPhone,drivercd;
	private RelativeLayout addDrivers;
	private ImageView bookPhone;
	private ImageView img1, img2, img3;
	private OnSweetClickListener mCancelClickListener;
	private OnSweetClickListener mConfirmClickListener;

	public static final int NORMAL_TYPE = 0;
	public static final int ERROR_TYPE = 1;
	public static final int SUCCESS_TYPE = 2;
	public static final int WARNING_TYPE = 3;
	public static final int CUSTOM_IMAGE_TYPE = 4;

	// 取消运单
	public static final int INIT_CANCLE = 0;
	public static final int DONTWANT_CANCLE = 1;
	public static final int LOOKAGAIN_CANCLE = 2;
	public static final int HASOTHER_CANCLE = 3;
	public static final int ADD_DRIVERS = 5;

	public static final int NORMAL_OK = 6;
	public static final int TIME_OUT = 7;
	private int cancle = 0;
	private View backView;
	private JumpTran jumpTran;
	private CancleMsg cancleMsg;
	// 设置按钮背景
	private Drawable confirmBg;
	private Drawable cancelBg;
	private String addText;
	private SpannableString mSpannableString;

	public static interface OnSweetClickListener {
		public void onClick(SweetAlertDialog sweetAlertDialog, int cancle);
	}

	@Override
	public void onDetachedFromWindow() {
		super.onDetachedFromWindow();
//		BusProvider.getInstance().unregister(this);
		EventBus.getDefault().unregister(this);
	}

	public SweetAlertDialog(Context context) {
		this(context, NORMAL_TYPE);
	}

	public SweetAlertDialog setBackView(View view) {
		this.backView = view;
		backView.setVisibility(View.VISIBLE);
		return this;
	}

	public SweetAlertDialog(Context context, int alertType) {
		super(context, R.style.alert_dialog);
		setCancelable(false);
		setCanceledOnTouchOutside(false);
		mAlertType = alertType;
		mErrorInAnim = OptAnimationLoader.loadAnimation(getContext(),
				R.anim.error_frame_in);
		mErrorXInAnim = (AnimationSet) OptAnimationLoader.loadAnimation(
				getContext(), R.anim.error_x_in);
		// 2.3.x system don't support alpha-animation on layer-list drawable
		// remove it from animation set
		if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
			List<Animation> childAnims = mErrorXInAnim.getAnimations();
			int idx = 0;
			for (; idx < childAnims.size(); idx++) {
				if (childAnims.get(idx) instanceof AlphaAnimation) {
					break;
				}
			}
			if (idx < childAnims.size()) {
				childAnims.remove(idx);
			}
		}
		mSuccessBowAnim = OptAnimationLoader.loadAnimation(getContext(),
				R.anim.success_bow_roate);
		mSuccessLayoutAnimSet = (AnimationSet) OptAnimationLoader
				.loadAnimation(getContext(), R.anim.success_mask_layout);
		mModalInAnim = (AnimationSet) OptAnimationLoader.loadAnimation(
				getContext(), R.anim.modal_in);
		mModalOutAnim = (AnimationSet) OptAnimationLoader.loadAnimation(
				getContext(), R.anim.modal_out);
		mModalOutAnim.setAnimationListener(new Animation.AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {

			}

			@Override
			public void onAnimationEnd(Animation animation) {
				mDialogView.setVisibility(View.GONE);
				mDialogView.post(new Runnable() {
					@Override
					public void run() {
						SweetAlertDialog.super.dismiss();
					}
				});
			}

			@Override
			public void onAnimationRepeat(Animation animation) {

			}
		});
		// dialog overlay fade out
		mOverlayOutAnim = new Animation() {
			@Override
			protected void applyTransformation(float interpolatedTime,
					Transformation t) {
				WindowManager.LayoutParams wlp = getWindow().getAttributes();
				wlp.alpha = 1 - interpolatedTime;
				getWindow().setAttributes(wlp);
			}
		};
		mOverlayOutAnim.setDuration(120);
	}

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.alert_dialog);
//		BusProvider.getInstance().register(this);
        EventBus.getDefault().register(this);
		mDialogView = getWindow().getDecorView().findViewById(
				android.R.id.content);
		mTitleTextView = (TextView) findViewById(R.id.title_text);
		mtit1 = (TextView) findViewById(R.id.title_text1);
		mtit2 = (TextView) findViewById(R.id.title_text2);
		mContentTextView = (TextView) findViewById(R.id.content_text);
		mErrorFrame = (FrameLayout) findViewById(R.id.error_frame);
		mErrorX = (ImageView) mErrorFrame.findViewById(R.id.error_x);
		mSuccessFrame = (FrameLayout) findViewById(R.id.success_frame);
		mSuccessTick = (SuccessTickView) mSuccessFrame
				.findViewById(R.id.success_tick);
		mSuccessLeftMask = mSuccessFrame.findViewById(R.id.mask_left);
		mSuccessRightMask = mSuccessFrame.findViewById(R.id.mask_right);
		mCustomImage = (ImageView) findViewById(R.id.custom_image);
		mWarningFrame = (RelativeLayout) findViewById(R.id.warning_frame);
		mConfirmButton = (Button) findViewById(R.id.confirm_button);
		mCancelButton = (Button) findViewById(R.id.cancel_button);
		radioGroup = (RadioGroup) findViewById(R.id.cancle_radiogroup);
		driverName = (EditText) findViewById(R.id.alert_add_driver_name);
		driverPhone = (EditText) findViewById(R.id.alert_add_driver_phone);
		drivercd = (EditText) findViewById(R.id.alert_add_driver_cd);
		LinearLayout.LayoutParams paramsmWarningFrame = (android.widget.LinearLayout.LayoutParams) mWarningFrame
				.getLayoutParams();
		paramsmWarningFrame.height = ApplicationContext.getInstance()
				.getScreen_width() /4;
		addDrivers = (RelativeLayout) findViewById(R.id.alert_add_driver);
		radioGroup.setOnCheckedChangeListener(this);
		mConfirmButton.setOnClickListener(this);
		mCancelButton.setOnClickListener(this);
		bookPhone = (ImageView) findViewById(R.id.alert_add_driver_bookphone);
		bookPhone.setOnClickListener(this);
		img1 = (ImageView) findViewById(R.id.waybill_detail_onpath1);
		img2 = (ImageView) findViewById(R.id.waybill_detail_onpath2);
		img3 = (ImageView) findViewById(R.id.waybill_detail_onpath3);
		int width = ApplicationContext.getInstance().getScreen_width();
		LayoutParams params2 = (LayoutParams) driverName.getLayoutParams();
		params2.width = width /2;
		LayoutParams params3 = (LayoutParams) driverPhone.getLayoutParams();
		params3.width = width /2;
		LayoutParams paramscd = (LayoutParams) drivercd.getLayoutParams();
		paramscd.width = width /2;
		drivercd.setLayoutParams(paramscd);
		LayoutParams params6 = (LayoutParams) bookPhone.getLayoutParams();
		params6.width = width / 15;
		params6.height = width / 15;
		params6.bottomMargin = width / 42;
		params6.leftMargin = -(width / 13);
		android.widget.LinearLayout.LayoutParams params4 = (android.widget.LinearLayout.LayoutParams) mCancelButton
				.getLayoutParams();
		params4.width = width / 3;
		mCancelButton.setLayoutParams(params4);
		android.widget.LinearLayout.LayoutParams params5 = (android.widget.LinearLayout.LayoutParams) mConfirmButton
				.getLayoutParams();
		params5.width = width / 3;
		mConfirmButton.setLayoutParams(params5);
		addTextView = (TextView) findViewById(R.id.alert_add_driver_title);
		/*
		 * android.widget.LinearLayout.LayoutParams params7
		 * =(android.widget.LinearLayout.LayoutParams)
		 * addTextView.getLayoutParams(); params7.leftMargin = -width/20;
		 */
		setSpannableString(mSpannableString);
		setAddTextView(addText);
		setTitleText(mTitleText);
		setTewTitleText(mTitleText1);
		setContentText(mContentText);
		showCancelButton(mShowCancel);
		setCancelText(mCancelText);
		setCancelBg(cancelBg);
		setConfirmBg(confirmBg);
		setConfirmText(mConfirmText);
		changeAlertType(mAlertType, true);
		if (mAlertType == ADD_DRIVERS) {
			addTextView.setVisibility(View.VISIBLE);
		}
		// 显示的坐标
		int screen_width = ApplicationContext.getInstance().getScreen_width();
		Window dialogWindow = this.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(Gravity.TOP);
		LinearLayout linearLayout = (LinearLayout) findViewById(R.id.loading);
		lp.y = screen_width/6; // 新位置Y坐标
		lp.width = (screen_width * 2 / 3) * 3 / 2; // 宽度
		if (mAlertType == SweetAlertDialog.WARNING_TYPE) {
			lp.height = screen_width; // 高度
		} else if (mAlertType == SweetAlertDialog.ADD_DRIVERS) {
//			lp.height = screen_width*2 ; // 高度
		}else {
			lp.height = screen_width * 2 / 3; // 高度
		}
		// 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
		// dialog.onWindowAttributesChanged(lp);
		dialogWindow.setAttributes(lp);

	}

	private void restore() {
		mCustomImage.setVisibility(View.GONE);
		mErrorFrame.setVisibility(View.GONE);
		mSuccessFrame.setVisibility(View.GONE);
		mWarningFrame.setVisibility(View.GONE);
		mErrorFrame.clearAnimation();
		mErrorX.clearAnimation();
		mSuccessTick.clearAnimation();
		mSuccessLeftMask.clearAnimation();
		mSuccessRightMask.clearAnimation();
	}

	private void playAnimation() {
		if (mAlertType == ERROR_TYPE) {
			mErrorFrame.startAnimation(mErrorInAnim);
			mErrorX.startAnimation(mErrorXInAnim);
		} else if (mAlertType == SUCCESS_TYPE) {
			mSuccessTick.startTickAnim();
			mSuccessRightMask.startAnimation(mSuccessBowAnim);
		}
	}

	private void changeAlertType(int alertType, boolean fromCreate) {
		mAlertType = alertType;
		// call after created views
		if (mDialogView != null) {
			if (!fromCreate) {
				// restore all of views state before switching alert type
				restore();
			}
			switch (mAlertType) {
			case ERROR_TYPE:
				mErrorFrame.setVisibility(View.VISIBLE);
				break;
			case SUCCESS_TYPE:
				mSuccessFrame.setVisibility(View.VISIBLE);
				// initial rotate layout of success mask
				mSuccessLeftMask.startAnimation(mSuccessLayoutAnimSet
						.getAnimations().get(0));
				mSuccessRightMask.startAnimation(mSuccessLayoutAnimSet
						.getAnimations().get(1));
				break;
			case WARNING_TYPE:
				int width = ApplicationContext.getInstance().getScreen_width();
				LinearLayout.LayoutParams params = (android.widget.LinearLayout.LayoutParams) mContentTextView.getLayoutParams();
				params.topMargin=-width/10;
				mWarningFrame.setVisibility(View.VISIBLE);
				break;
			case ADD_DRIVERS:
				addDrivers.setVisibility(View.VISIBLE);
				break;
			case CUSTOM_IMAGE_TYPE:
				setCustomImage(mCustomImgDrawable);
				break;
			case TIME_OUT:
				android.widget.LinearLayout.LayoutParams params5 = (android.widget.LinearLayout.LayoutParams) mConfirmButton
						.getLayoutParams();
				params5.width = ApplicationContext.getInstance()
						.getScreen_width() *2/3+60;
				mConfirmButton.setLayoutParams(params5);
				break;
			case NORMAL_OK:
				mConfirmButton.setVisibility(View.GONE);
				mContentTextView.setGravity(Gravity.CENTER);
				Handler handler = new Handler();
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						jumpTran.toJump(SweetAlertDialog.this);

					}
				}, 3000);
				break;
			}
			if (!fromCreate) {
				playAnimation();
			}
		}
	}

	public int getAlerType() {
		return mAlertType;
	}

	public void changeAlertType(int alertType) {
		changeAlertType(alertType, false);
	}

	public String getTitleText() {
		return mTitleText;
	}

	public SweetAlertDialog setTitleText(String text) {
		mTitleText = text;
		if (mTitleTextView != null && mTitleText != null) {
			mTitleTextView.setText(mTitleText);
			if (StringUtil.isEmpty(text)) {
				mTitleTextView.setVisibility(View.GONE);
			}
		}
		return this;
	}

	// 修改添加司机文本
	public SweetAlertDialog setAddTextView(String text) {
		addText = text;
		if (addTextView != null && addText != null) {

			addTextView.setText(addText);
			LogUtils.e("text:" + text + addText);
		}
		return this;
	}

	public SweetAlertDialog setTewTitleText(String text) {

		mTitleText1 = text;
		if (mtit1 != null && mTitleText1 != null) {
			mtit1.setText(mTitleText1);
			mtit1.setVisibility(View.VISIBLE);
			mtit2.setVisibility(View.VISIBLE);
		}

		return this;
	}

	public SweetAlertDialog setJump(JumpTran jumpTran) {

		this.jumpTran = jumpTran;

		return this;
	}

	public SweetAlertDialog setCancleMsg(CancleMsg cancleMsg) {

		this.cancleMsg = cancleMsg;

		return this;
	}

	public SweetAlertDialog setCustomImage(Drawable drawable) {
		mCustomImgDrawable = drawable;
		if (mCustomImage != null && mCustomImgDrawable != null) {
			mCustomImage.setVisibility(View.VISIBLE);
			mCustomImage.setImageDrawable(mCustomImgDrawable);
		}
		return this;
	}

	public SweetAlertDialog setCustomImage(int resourceId) {
		return setCustomImage(getContext().getResources().getDrawable(
				resourceId));
	}

	public String getContentText() {
		return mContentText;
	}

	public SweetAlertDialog setContentText(String text) {
		mContentText = text;
		if (mContentTextView != null && mContentText != null) {
			mContentTextView.setVisibility(View.VISIBLE);
			mContentTextView.setText(mContentText);

			if (StringUtil.isEmpty(text)) {
				mContentTextView.setVisibility(View.GONE);
			}
			SpannableStringBuilder builder = new SpannableStringBuilder(
					text);
			if (text.contains("垫")) {
				
				ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
				int lent = text.indexOf("申请");
				builder.setSpan(redSpan, lent, lent + 4,
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				mContentTextView.setText(builder);
			}else {
				String cont = " 您的车都在拉货呢，卸完\n  \n货再抢吧！";
				String contt = " 取消运单次数过多，今天\n  \n不能再抢单了";
				String cString = "多次取消运单，会造成当日\n  \n不能抢单，请慎重考虑。";
				if (text.equals(contt)||text.equals(cont)) {
				
				AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(4, true);
				builder.setSpan(sizeSpan,12, 16,
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				mContentTextView.setText(builder);
				}else if (text.equals(cString)) {
					AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(4, true);
					builder.setSpan(sizeSpan,13, 16,
							Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					mContentTextView.setText(builder);
				}
			}
		}
		return this;
	}

	public SweetAlertDialog setSpannableString(SpannableString spannableString) {
		mSpannableString = spannableString;
		if (mContentTextView != null && mSpannableString != null) {
			mContentTextView.setVisibility(View.VISIBLE);
			mContentTextView.setText(mSpannableString);
			mContentTextView
					.setMovementMethod(LinkMovementMethod.getInstance());
			if (StringUtil.isEmpty(spannableString)) {
				mContentTextView.setVisibility(View.GONE);
			}
		}
		return this;
	}

	public SweetAlertDialog setContentTextPading() {

		if (mContentTextView != null) {
			mContentTextView.setPadding(30, 0, 30, 0);

		}
		return this;
	}

	public boolean isShowCancelButton() {
		return mShowCancel;
	}

	public SweetAlertDialog showCancelButton(boolean isShow) {
		mShowCancel = isShow;
		if (mCancelButton != null) {
			mCancelButton.setVisibility(mShowCancel ? View.VISIBLE : View.GONE);
		}
		return this;
	}

	public String getCancelText() {
		return mCancelText;
	}

	public SweetAlertDialog setCancelText(String text) {
		mCancelText = text;
		if (mCancelButton != null && mCancelText != null) {
			mCancelButton.setText(mCancelText);
		}
		return this;
	}

	@SuppressLint("NewApi")
	public SweetAlertDialog setCancelBg(Drawable drawable) {
		cancelBg = drawable;
		if (mCancelButton != null && cancelBg != null) {
			mCancelButton.setBackground(drawable);
		}
		return this;
	}

	public String getConfirmText() {
		return mConfirmText;
	}

	public SweetAlertDialog setConfirmText(String text) {
		mConfirmText = text;
		if (mConfirmButton != null && mConfirmText != null) {
			mConfirmButton.setText(mConfirmText);
		}
		return this;
	}

	@SuppressLint("NewApi")
	public SweetAlertDialog setConfirmBg(Drawable drawable) {
		confirmBg = drawable;
		if (mConfirmButton != null && confirmBg != null) {
			mConfirmButton.setBackground(drawable);

		}
		return this;
	}

	public SweetAlertDialog setCancelClickListener(OnSweetClickListener listener) {
		mCancelClickListener = listener;
		return this;
	}

	public SweetAlertDialog setConfirmClickListener(
			OnSweetClickListener listener) {
		mConfirmClickListener = listener;
		return this;
	}

	protected void onStart() {
		mDialogView.startAnimation(mModalInAnim);
		playAnimation();
	}

	public void dismiss() {
		mConfirmButton.startAnimation(mOverlayOutAnim);
		mDialogView.startAnimation(mModalOutAnim);
	}

	@Override
	public void onClick(View v) {

		if (v.getId() == R.id.cancel_button) {
			if (mCancelClickListener != null) {
				if (mAlertType == WARNING_TYPE) {
					if (cancle != INIT_CANCLE) {
						mCancelClickListener.onClick(SweetAlertDialog.this,
								cancle);
						if (backView != null) {
							backView.setVisibility(View.GONE);
						}
					} else {
						MyToast.showDefaltToast("请选择取消原因");
					}
				} else {

					if (backView != null) {
						backView.setVisibility(View.GONE);
					}
					mCancelClickListener.onClick(SweetAlertDialog.this,
							INIT_CANCLE);
				}
			} else {
				dismiss();
			}
		} else if (v.getId() == R.id.confirm_button) {
			if (mConfirmClickListener != null) {
				if (mAlertType == WARNING_TYPE) {
					mConfirmClickListener
							.onClick(SweetAlertDialog.this, cancle);
					if (backView != null) {
						backView.setVisibility(View.GONE);
					}

				} else {
					if (backView != null) {
						backView.setVisibility(View.GONE);
					}
					mConfirmClickListener
							.onClick(SweetAlertDialog.this, cancle);
				}
			} else {
				dismiss();
			}
		} else if (v.getId() == R.id.alert_add_driver_bookphone) {

		}
	}

	@Override
	public void onCheckedChanged(RadioGroup arg0, int arg1) {
		switch (arg1) {
		case R.id.cancle_dontwant:
			cancle = DONTWANT_CANCLE;
			img1.setSelected(true);
			img2.setSelected(false);
			img3.setSelected(false);
			cancleMsg.cancle("不想接了");
			break;
		case R.id.cancle_look_again:
			cancle = LOOKAGAIN_CANCLE;
			img1.setSelected(false);
			img2.setSelected(true);
			img3.setSelected(false);
			cancleMsg.cancle("再挑挑");
			break;
		case R.id.cancle_has_other:
			cancle = HASOTHER_CANCLE;
			img1.setSelected(false);
			img2.setSelected(false);
			img3.setSelected(true);
			cancleMsg.cancle("接了别的活");
			break;
		default:
			break;
		}
	}

	public interface JumpTran {
		void toJump(SweetAlertDialog dia);
	}

	public interface CancleMsg {
		void cancle(String msg);
	}
}
